<template>
  <div class="editForm">
    <div v-if="isAdd">
      <div class="user-form">
        <span class="user-form-title">用户基本信息</span>
        <Form :model="modelForm" ref="editForm" class="user-info ivu-form-no-margin-bottom" :rules="rule" :label-width="80">
          <Row :gutter="32" class="code-row-bg">
            <Col span="6">
              <!-- 用户账号 -->
              <Form-item prop="userId" :label="$t('module.userManage.userAccount')">
                <Input
                  v-model="modelForm.userId"
                  :placeholder="$t('module.userManage.placeholder.account')"
                  :maxlength="50"
                  style="-width: 250px"
                />
              </Form-item>
            </Col>
            <Col span="6">
              <!-- 用户名称 必填-->
              <Form-item prop="userName" :label="$t('module.userManage.name')">
                <Input
                  v-model="modelForm.userName"
                  :placeholder="$t('module.userManage.placeholder.userName')"
                  style="-width: 250px"
                />
              </Form-item>
            </Col>
            <Col span="6">
              <!-- 手机号码 必填-->
              <Form-item prop="mobile" :label="$t('module.userManage.cellPhoneNumber')">
                <Input
                  v-model="modelForm.mobile"
                  :placeholder="$t('module.userManage.placeholder.phoneNumber')"
                />
              </Form-item>
            </Col>
            <Col span="6">
              <!-- 电子邮箱 -->
              <Form-item prop="email" :label="$t('module.userManage.email')">
                <Input
                  v-model="modelForm.email"
                  :placeholder="$t('module.userManage.placeholder.email')"
                  :maxlength="32"
                />
              </Form-item>
            </Col>
            <Col span="6" v-show="isPlatform">
              <!-- 用户类型-->
              <Form-item prop="category" :label="$t('module.userManage.userRoles')">
                <Select
                  v-model="modelForm.category"
                  @on-change="handleUserCategory"
                  :disabled="currentUserInfo.category != 1"
                >
                  <Option v-for="item in categoryList" :value="item.value" :key="item.value">{{ item.label }}</Option>
                </Select>
              </Form-item>
            </Col>
            <Col span="6">
              <!-- 所属组织 -->
              <Form-item prop="orgName" :label="$t('module.userManage.organization')">
                <Input
                  type="text"
                  style="position: absolute; z-index: 999; opacity: 0; width: 80%"
                  @click.native="selectOrganization"
                ></Input>
                <Input
                  type="text"
                  icon="ios-paper-plane-outline"
                  :maxlength="30"
                  v-model.trim="modelForm.orgName"
                  :placeholder="$t('module.userManage.selectOrganization')"
                  clearable
                  readonly
                  @on-click="selectOrganization"
                  @on-clear="clearOrganization"
                ></Input>
              </Form-item>
            </Col>
            <Col span="6" v-if="modelForm.orgName">
              <!-- 关联员工 -->
              <Form-item prop="employeeId" :label="$t('module.userManage.associatedEmployees')">
                <div class="form-choice-wrap">
                  <Input
                    type="text"
                    style="position: absolute; z-index: 999; opacity: 0; width: 80%"
                    @click.native="selectEmployee"
                  ></Input>
                  <Input
                    v-model="modelForm.employeeName"
                    :maxlength="20"
                    icon="ios-paper-plane-outline"
                    readonly
                    clearable
                    @on-click="selectEmployee"
                    :placeholder="$t('module.userManage.placeholder.employeeId')"
                  />
                </div>
              </Form-item>
            </Col>
            <Col span="6">
              <!-- 状态 -->
              <Form-item prop="locked" :label="$t('common.status')" v-show="!showTenantCode">
                <i-switch size="large" true-value="0" false-value="1" v-model="modelForm.locked" :disabled="modelForm.userName == 'admin'">
                  <template slot="open">
                    <span>{{$t("common.enable")}}</span>
                  </template>
                  <template slot="close">
                    <span>{{$t("common.disable")}}</span>
                  </template>
                </i-switch>
                <!-- <RadioGroup v-model="modelForm.locked">
                  <Radio label="0" :disabled="modelForm.userName == 'admin'">{{ $t("common.enable") }}</Radio>
                  <Radio label="1" :disabled="modelForm.userName == 'admin'">{{ $t("common.disable") }}</Radio>
                </RadioGroup> -->
              </Form-item>
            </Col>
            <Col span="6">
              <!-- 状态 -->
              <Form-item prop="locked" :label="$t('common.status')" v-show="showTenantCode">
                <i-switch size="large" true-value="0" false-value="1" v-model="modelForm.locked">
                  <template slot="open">
                    <span>{{$t("common.enable")}}</span>
                  </template>
                  <template slot="close">
                    <span>{{$t("common.disable")}}</span>
                  </template>
                </i-switch>
                <!-- <RadioGroup v-model="modelForm.locked">
                  <Radio label="0">{{ $t("common.enable") }}</Radio>
                  <Radio label="1">{{ $t("common.disable") }}</Radio>
                </RadioGroup> -->
              </Form-item>
            </Col>
            <Col span="24">
              <!-- 用户头像 -->
              <Form-item class="last-item" prop="avatar" label="用户头像">
                <div class="user-img" v-show="!modelForm.avatar">
                  <Upload
                    @click="() => {}"
                    ref="uploadFile"
                    :before-upload="handleUpload"
                    :show-upload-list="false"
                    :accept="accept.join()"
                    :format="format"
                    type="drag"
                    style="display: inline-block;width:80px;"
                    action=""
                  >
                    <div class="upload-icon">
                      <Icon type="ios-camera" size="30"></Icon>
                    </div>
                  </Upload>
                  <p>仅支持{{format.join(',')}}格式</p>
                </div>

                <div v-if="modelForm.avatar" class="img-item">
                  <img :src="modelForm.avatar" fit="cover" width="80px" height="80px" />
                  <div  class="demo-upload-list-cover">
                      <Icon v-if="modelForm.avatar" type="ios-eye-outline" @click="handleView()"></Icon>
                      <Icon type="ios-trash-outline" @click="handleRemove()"></Icon>
                  </div>
                </div>
              </Form-item>
            </Col>
          </Row>
        </Form>
      </div>


      <!-- 角色分配 -->
      <div class="role-assignment" style="max-height: 300px" v-if="hasRoleAssignment">
        <role-assignment :userId="userInfo.id"></role-assignment>
      </div>

      <!-- 分配应用 -->
      <div class="user-app" v-if="modelForm.tenantCode && ACCESSIBLE_APP">
        <div v-if="!this.userInfo.id || (show_allotapp && modelForm.tenantCode)" class="app-title"> <span class="title">可访问应用授权</span></div>
        <allot-app
          v-if="!this.userInfo.id || (show_allotapp && modelForm.tenantCode)"
          :tenantCodeAndUser="tenantCodeAndUser"
          :selectApp="currentAppVos"
          :defaultSelectApp="defaultSelectApp"
          :userInfo="userInfo"
          @handleAllotApp="getSelectAllotApp"
        />
      </div>
    </div>
    <div v-else>
      <div class="user-form">
         <span class="user-form-title">用户基本信息</span>
        <Form :model="modelForm" ref="editForm" class="user-info ivu-form-no-margin-bottom" :rules="rule" :label-width="80">
          <Row :gutter="32" class="code-row-bg">
            <Col span="6">
              <!-- 用户账号 -->
              <Form-item prop="userId" :label="$t('module.userManage.userAccount')">
                <Input
                  v-model="modelForm.userId"
                  :placeholder="$t('module.userManage.placeholder.account')"
                  :maxlength="50"
                  disabled
                  style="-width: 250px"
                />
              </Form-item>
            </Col>
            <Col span="6">
              <!-- 用户名称 必填-->
              <Form-item prop="userName" :label="$t('module.userManage.name')">
                <Input
                  :disabled="!USER_DETAIL || this.isLdapFromSync || disabledSwitchLdapUserStatus"
                  v-model="modelForm.userName"
                  :placeholder="$t('module.userManage.placeholder.userName')"
                  :maxlength="30"
                  style="-width: 250px"
                />
              </Form-item>
            </Col>
            <Col span="6">
              <!-- 手机号码 必填-->
              <Form-item prop="mobile" :label="$t('module.userManage.cellPhoneNumber')">
                <Input
                  :disabled="!USER_DETAIL || this.isLdapFromSync || disabledSwitchLdapUserStatus"
                  v-model="modelForm.mobile"
                  :placeholder="$t('module.userManage.placeholder.phoneNumber')"
                />
              </Form-item>
            </Col>
            <Col span="6">
              <!-- 电子邮箱 -->
              <Form-item prop="email" :label="$t('module.userManage.email')">
                <Input
                  :disabled="!USER_DETAIL || this.isLdapFromSync || disabledSwitchLdapUserStatus"
                  v-model="modelForm.email"
                  :placeholder="$t('module.userManage.placeholder.email')"
                  :maxlength="32"
                />
              </Form-item>
            </Col>
            <Col span="6">
              <!-- 所属组织 -->
              <Form-item prop="orgName" :label="$t('module.userManage.organization')">
                <Input
                  type="text"
                  style="position: absolute; z-index: 999; opacity: 0; width: 80%"
                  @click.native="selectOrganization"
                  :disabled="isLdapFromSync"
                ></Input>
                <Input
                  type="text"
                  :maxlength="30"
                  v-model.trim="modelForm.orgName"
                  :placeholder="$t('module.userManage.selectOrganization')"
                  icon="ios-paper-plane-outline"
                  :clearable="USER_DETAIL "
                  readonly
                  @on-click="selectOrganization"
                  :disabled="!USER_DETAIL || isLdapFromSync"
                  @on-clear="clearOrganization"
                ></Input>
              </Form-item>
            </Col>
            <Col span="6" v-if="modelForm.orgName || this.isLdapFromPlatform">
              <!-- 关联员工 -->
              <Form-item prop="employeeId" :label="$t('module.userManage.associatedEmployees')">
                <div class="form-choice-wrap">
                  <Input
                    type="text"
                    style="position: absolute; z-index: 999; opacity: 0; width: 80%"
                    @click.native="selectEmployee"
                    :disabled="!USER_DETAIL || disabledSwitcheEployee"
                  ></Input>
                  <Input
                    v-model="modelForm.employeeName"
                    :maxlength="20"
                    icon="ios-paper-plane-outline"
                    readonly
                    :clearable="USER_DETAIL && !disabledSwitcheEployee"
                    :disabled="!USER_DETAIL || disabledSwitcheEployee"
                    @on-click="selectEmployee"
                    :placeholder="$t('module.userManage.placeholder.employeeId')"
                  />
                </div>
              </Form-item>
            </Col>

            <Col span="6" v-if="!showTenantCode">
              <!-- 状态 -->
              <Form-item prop="locked" :label="$t('common.status')" >
                <i-switch size="large" true-value="0" false-value="1" v-model="modelForm.locked" :disabled="!USER_DETAIL || modelForm.userName == 'admin' || disabledSwitchLdapUserStatus">
                  <template slot="open">
                    <span>{{$t("common.enable")}}</span>
                  </template>
                  <template slot="close">
                    <span>{{$t("common.disable")}}</span>
                  </template>
                </i-switch>
                <!-- <RadioGroup v-model="modelForm.locked">
                  <Radio label="0" :disabled="!USER_DETAIL || modelForm.userName == 'admin'">
                    {{ $t("common.enable") }}
                  </Radio>
                  <Radio label="1" :disabled="!USER_DETAIL || modelForm.userName == 'admin'">
                    {{ $t("common.disable") }}
                  </Radio>
                </RadioGroup> -->
              </Form-item>
            </Col>
            <Col span="6" v-if="showTenantCode">
              <!-- 状态 -->
              <Form-item prop="locked" :label="$t('common.status')" >
                <i-switch size="large" true-value="0" false-value="1" v-model="modelForm.locked" :disabled="!USER_DETAIL || this.isLdapFromSync || disabledSwitchLdapUserStatus">
                  <template slot="open">
                    <span>{{$t("common.enable")}}</span>
                  </template>
                  <template slot="close">
                    <span>{{$t("common.disable")}}</span>
                  </template>
                </i-switch>
                <!-- <RadioGroup v-model="modelForm.locked">
                  <Radio label="0" :disabled="!USER_DETAIL || this.isLdapFromSync">{{ $t("common.enable") }}</Radio>
                  <Radio label="1" :disabled="!USER_DETAIL || this.isLdapFromSync">{{ $t("common.disable") }}</Radio>
                </RadioGroup> -->
              </Form-item>
            </Col>
            <Col span="24">
              <!-- 用户头像 -->
              <Form-item class="last-item" prop="avatar" label="用户头像">
                <div class="user-img" v-show="!modelForm.avatar">
                  <Upload
                    @click="() => {}"
                    ref="uploadFile"
                    :disabled="!USER_DETAIL || this.isLdapFromSync"
                    :before-upload="handleUpload"
                    :show-upload-list="false"
                    :accept="accept.join()"
                    :format="format"
                    type="drag"
                    style="display: inline-block;width:80px;"
                    action=""
                  >
                    <div class="upload-icon">
                      <Icon type="ios-camera" size="30"></Icon>
                    </div>
                  </Upload>
                  <p>仅支持{{format.join(',')}}格式</p>
                </div>

                <div v-if="modelForm.avatar" class="img-item">
                  <img :src="modelForm.avatar" fit="cover" width="80px" height="80px" />
                  <div  class="demo-upload-list-cover">
                      <Icon v-if="modelForm.avatar" type="ios-eye-outline" @click="handleView()"></Icon>
                      <Icon type="ios-trash-outline" v-if="!(!USER_DETAIL || this.isLdapFromSync)" @click="handleRemove()"></Icon>
                  </div>
                </div>
              </Form-item>
            </Col>
          </Row>
        </Form>
      </div>


      <!-- 角色分配 -->
      <div class="role-assignment" style="max-height: 300px" v-if="hasRoleAssignment">
        <role-assignment :userId="userInfo.id"></role-assignment>
      </div>

      <!-- 分配应用 -->
      <div class="user-app" v-if="ACCESSIBLE_APP">
        <div class="app-title"> <span class="title">可访问应用授权</span></div>
        <allot-app
          v-if="!this.userInfo.id || (show_allotapp && modelForm.tenantCode)"
          :tenantCodeAndUser="tenantCodeAndUser"
          :selectApp="currentAppVos"
           :defaultSelectApp="defaultSelectApp"
          :userInfo="userInfo"
          @handleAllotApp="getSelectAllotApp"
        />
      </div>
    </div>
    <ImagePreview :visible="visible" :currentImg="currentImg" @close="() => {visible = false}"/>
  </div>
</template>

<script>
import locales from "./locales.js";
import userManageAPI from "@/api/userManageApi";
import SelectPerson from "./SelectPerson.vue";
import selectOrganization from "./selectOrganization.vue";
import ImagePreview from './ImagePreview.vue';
import AllotApp from "./AllotApp";
import RoleAssignment from "./RoleAssignment"; // 角色分配
// import AllotApp from "./AllotApp"; // 分配应用
import { mapMutations } from "vuex";
import { CoreModuleName } from "@/const";
import { validateMobile } from "@/tools/util.js"
// 用于判断登录用户类型
const RIPPLES = "ripples";

export default {
  components: {
    AllotApp,
    RoleAssignment,
    ImagePreview
  },
  props: {
    userInfo: {
      type: Object,
      default: () => {
        return {};
      }
    },
    // UI资源权限
    USER_DETAIL: {
      type: Boolean,
      default() {
        return false;
      }
    },
    ACCESSIBLE_APP: {
      type: Boolean,
      default() {
        return false;
      }
    }
  },
  mixins: [locales],
  data() {
    return {
      fileSize: 2,
      format: ['jpeg', 'jpg', 'png'],
      accept: ['.jpeg','.jpg', '.png'],
      uploadFile: '',
      currentImg: '',
      visible: false,
      isAdd: true,
      currentUserInfo: $store.state[CoreModuleName].userInfo,
      tenantCodeAndUser: {
        tenantCode: "",
        category: 0
      },
      userId: this.userInfo.id, // 用于判断是新增，还是编辑
      showTenantCode: true,
      categoryList: [
        {
          value: 1,
          label: this.$t("module.userManage.platformAdmin") //平台管理员
        },
        {
          value: 2,
          label: this.$t("module.userManage.tenantAdmin") // 租户管理员
        },
        {
          value: 3,
          label: this.$t("module.userManage.ordinaryUser") // 普通用户
        },
        {
          value: 4,
          label: this.$t("module.userManage.developerUser") // 开发者
        }
      ],
      // employeeName: this.userInfo.employeeName,
      // 保存初始数据
      initData: {
        locked: "", // 状态
        // 选中数据
        selfBuiltApp: [],
        thirdPartyApp: []
      },
      selfBuiltArr: [], //参数：自建的选中应用编码
      thirdPartyArr: [], //参数：第三方的选中应用编码
      selfBuiltSign: false, // 标识：代表自建应用的选择框是否改变过
      thirdPartySign: false, // 标识：代表第三方应用的选择框是否改变过
      modelForm: {
        orgName: this.userInfo.orgName,
        orgPath: this.userInfo.orgPath,
        orgId: this.userInfo.orgId,
        // orgCodeFullPath: this.userInfo.orgCodeFullPath,

        orgCode: this.userInfo.orgCode,
        orgCodeFullPath: this.userInfo.orgCodeFullPath,
        mdmFullCodePath: this.userInfo.mdmFullCodePath,
        mdmOrgName: this.userInfo.mdmOrgName,
        mdmFullNamePath: this.userInfo.mdmFullNamePath,
        // organization: this.userInfo.organization,
        id: this.userInfo.id,
        userId: this.userInfo.account || this.userInfo.userId, // 用户账号
        userName: this.userInfo.userName || this.userInfo.username,
        email: this.userInfo.email,
        mobile: this.userInfo.mobile,
        tenantCode: this.userInfo.tenantCode, //兼容医药, 使用 tenantCode
        locked: this.userInfo.locked || "0",
        employeeId: this.userInfo.employeeId,
        employeeName: this.userInfo.employeeName,
        category: this.userInfo.category, // 用户类型
        avatar: this.userInfo.avatar, // 用户类型
        // assignUserVos: [],
        addAssignUserVos: [],
        delAssignUserVos: []
      },
      addApp: [], //新增的应用
      delApp: [], //删除的应用
      currentAppVos: [], // 选中的全部APP
      defaultSelectApp: [],
      selfBuiltApp: [], // 选中的自建APP
      thirdPartyApp: [], // 选中的第三方APP
      cancelSelfBuiltApp: [], //取消的自建应用
      cancelThirdPartyApp: [], //取消的第三方应用
      show_allotapp: false,
      rule: {
        userId: [
          {
            required: false,
            type: 'string',
            max: 30,
            message: this.$t("common.warning.lengMaxFormat", ['30'])
          }, 
          {
            type: 'string',
            pattern: /^[a-zA-Z0-9|_|\-|\.]+$/,
            message: this.$t("common.warning.codeFormat")
          }
          // {
          //   required: false,
          //   trigger: "blur",
          //   validator: (rule, value, callback) => {
          //     let reg = /^[0-9a-zA-Z-_]{1,}$/gi;
          //     if (value === undefined || value.trim() === "") {
          //       callback();
          //     } else if (!reg.test(value.trim())) {
          //       callback(this.$t("module.userManage.warning.enterAccount"));
          //     } else {
          //       callback();
          //     }
          //   }
          // }
        ],
        userName: [
          {
            required: true,
            message: this.$t("module.userManage.warning.enterUserName"),
            trigger: "blur"
          },
          {
            type: 'string',
            max: 50,
            message: this.$t("common.warning.lengMaxFormat", ['50'])
          },
          {
            type: 'string',
            pattern: /[\u4E00-\u9FA5]|[A-Z]|[a-z]|[0-9]/,
            message: this.$t("common.warning.nameFormat")
          }
        ],
        email: [
          {
            required: false,
            message: this.$t("module.userManage.warning.enterEmail"),
            trigger: "blur"
          },
          { pattern: /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/, message: this.$t("module.userManage.warning.enterErrorEmail"), trigger: 'blur'}
        ],
        mobile: [
          {
            required: true,
            message: this.$t("module.userManage.warning.enterCellPhoneNumber"),
            trigger: "blur"
          },
          // {
          //   type: "number",
          //   validator: (rule, value, callback) => {
          //     let reg = /^[1][3,4,5,6,7,8,9]\d{9}$/gi;
          //     if (!reg.test(value)) {
          //       callback(this.$t("module.userManage.warning.enterCorrectTel"));
          //     } else {
          //       callback();
          //     }
          //   },
          //   trigger: "blur"
          // }
          {
            type: "number",
            validator: validateMobile.bind(this),
            trigger: "blur"
          }
        ],
        category: [
          {
            type: "number",
            required: true,
            message: this.$t("module.userManage.warning.selectUserCategory"),
            trigger: "change"
          }
        ],
        tenantCode: [
          {
            required: true,
            message: this.$t("module.userManage.warning.selectTenantCode"),
            trigger: "change"
          }
        ],
        orgName: [
          {
            required: true,
            message: this.$t("module.userManage.selectOrganization"),
            trigger: "change"
          }
        ]
      },
      actions: [
        {
          text: this.$t("common.save"),
          theme: "primary",
          handle: () => {
            this.save();
          },
          loading: false
        },
        {
          text: this.$t("common.close"),
          handle: () => {
            this.$emit("Close");
          }
        }
      ]
    };
  },
  computed: {
    // 判断是否是数字化平台：1. 所属租户是数字化平台; 2. 用户类型是平台管理员或者租户管理员
    is_Digitalplatform() {
      // 当前登录用户
      let currentUserInfo = this.currentUserInfo;
      let curTenantCode = currentUserInfo.tenantCode && currentUserInfo.tenantCode.toLowerCase() === RIPPLES;
      // let curUserCategory = currentUserInfo.category; // 用户类型: 1. 平台管理员 2. 租户管理员 3. 普通用户

      // if (curTenantCode || curUserCategory === 1 || curUserCategory === 2) {
      if (curTenantCode) {
        return true;
      } else {
        return false;
      }
    },
    //判断是否是平台管理员
    isPlatform() {
      //当前登录用户
      let currentUserInfo = this.currentUserInfo;
      let curUserCategory = currentUserInfo.category; //用户类型：1.平台管理员 2.租户管理员 3.普通用户
      if (curUserCategory == 1) {
        return true;
      } else {
        return false;
      }
    },
    // 放开如果是数字化平台类型则不显示角色分配管理数据
    hasRoleAssignment() {
      // if (!this.is_Digitalplatform && this.userId) {
      if (this.userId) {
        return true;
      }
      return false;
    },
    disabledSwitchLdapUserStatus() {
      const ldapTypes = [4, 5]
      if (ldapTypes.includes(this?.userInfo?.type) && this?.userInfo?.locked === '0') {
        return true
      }
      return false
    },
    // 是否自建Ldap用户
    isLdapFromPlatform(){
      return this.userInfo.type == 5
    },
    // 后台同步Ldap
    isLdapFromSync() {
      return this.userInfo.type == 4
    },
    // 是否禁用关联员工表单
    disabledSwitcheEployee() {
      return !!this.userInfo.employeeId && (this.isLdapFromSync || this.isLdapFromPlatform)
    }
  },
  created: function() {
    this.tenantCodeAndUser.tenantCode = this.userInfo.tenantCode;
    this.tenantCodeAndUser.category = this.userInfo.category;
    this.initUserEdit();
    this.initCategorySelect(this.is_Digitalplatform);

    // 设置弹窗Title
    if (this.userId) {
      // 编辑
      this.isAdd = false;
      this.$emit("SetTitle", this.$t("module.userManage.editUser"));
    } else {
      // 新增
      this.isAdd = true;
      this.$emit("SetTitle", this.$t("module.userManage.addUser"));
    }
    this.$emit("SetPageWidth", 734);
    this.$emit("SetPageActions", this.actions);
  },
  methods: {
    ...mapMutations($moduleName, [
      "setUserInfo"
    ]),
    handleView () {
      this.currentImg = this.modelForm.avatar;
      this.visible = true;
    },
    handleRemove() {
      this.modelForm.avatar = ''
      this.uploadFile = ''
    },
      //上传
    handleUpload(file) {
      if (file.size > 1024 * 1024 * this.fileSize) {
        this.$message.error('文件过大，请您按照要求上传待识别的文件')
        return false
      }
      let namelist = file.name.split('.')
      let currentType = this.format.find(
        item => namelist[namelist.length - 1] && item.includes(namelist[namelist.length - 1].toLocaleLowerCase())
      )
      this.uploadType = currentType
      if (!currentType) {
        this.$message.error('不支持该文件类型上传，请您按要求上传待识别的文件')
        return false
      }
      this.fileName = this.fileName ? this.fileName + '/' + file.name : this.fileName + file.name
      this.file = file
      const _this = this
      const reader = new FileReader()
      reader.readAsDataURL(file)
      reader.onload = function() {
        _this.uploadFile = reader.result
        _this.modelForm.avatar = reader.result
      }
      return false
    },
    initUserEdit() {
      if (this.userInfo.id) {
        // 通过ID获取当前编辑用户的数据
        userManageAPI.getUserInfoById({ id: this.userInfo.id, tenantCode: this.userInfo.tenantCode }).then(data => {
          this.modelForm.category = data.category;
          this.modelForm.orgCodeFullPath = data.orgCodeFullPath;
          this.modelForm.employeeName = data.employeeName;
          // 保存初始状态
          this.initData.locked = data.locked;
        });
        // 获取用户分配的应用
        userManageAPI
          .getAppListByUserId({ userId: this.userInfo.id, tenantCode: this.userInfo.tenantCode })
          .then(data => {
            this.currentAppVos = data;
            this.defaultSelectApp = data;
            // 此开关控制currentAppVos选中数据获取到了再去渲染子组件allot-app，否则会存在选中数据还未获取到，子组件已渲染完毕，导致列表应用没有选中
            this.show_allotapp = true;
            // 设置默认选择应用
            this.selfBuiltApp = this.currentAppVos.filter(item => item.applicationType === 0);
            this.thirdPartyApp = this.currentAppVos.filter(item => item.applicationType === 1);

            // 保存自建应用&第三方应用的选中数据
            this.initData.selfBuiltApp = this.selfBuiltApp.map(item => item.applicationCode);
            this.initData.thirdPartyApp = this.thirdPartyApp.map(item => item.applicationCode);
          });
      }
    },
    // 选择组所属组织
    selectOrganization() {
      // 用户来源是ldap时不允许编辑
      if (!this.USER_DETAIL || this.isLdapFromSync) {
        return;
      }
      new this.$pageModal(
        selectOrganization,
        {
          props: {}
        },
        data => {
          if (data) {
            // 清除关联员工
            if (this.modelForm.orgId !== data.orgId) {
              this.clearOrganization();
            }
            // orgCodeFullPath逻辑处理
            let orgPath = data.orgPath
            let orgPathWithoutTanent = orgPath
            let orgNamePath = data.orgNameFullPath
            let orgNamePathWithoutTanent = orgNamePath
            let tenantCode = data.tenantCode
            // 若一级路径跟租户编码一致，则移除
            if (orgPath.split('/')[0] == tenantCode) {
              let tenantName = orgNamePath.split('/')[0]
              orgPathWithoutTanent = orgPath.replace(tenantCode, '');
              orgNamePathWithoutTanent = orgNamePath.replace(tenantName, '');
            }

            this.modelForm.orgName = data.orgName;
            this.modelForm.orgId = data.orgId;
            this.modelForm.orgPath = orgPath;
            this.modelForm.orgCode = data.orgCode;
            this.modelForm.orgCodeFullPath = orgPathWithoutTanent;
            this.modelForm.mdmFullCodePath = orgPathWithoutTanent;
            this.modelForm.mdmOrgName = data.orgName;
            this.modelForm.mdmFullNamePath = orgNamePathWithoutTanent;
          }
        }
      );
    },
    // 清除所属组织
    clearOrganization() {
      if (this.isLdapFromPlatform) {
        return 
      }
      this.modelForm.employeeId = "";
      this.modelForm.employeeName = "";
      return;
    },
    // 关联员工弹窗
    selectEmployee() {
      if ((!this.isAdd && !this.USER_DETAIL) || this.isLdapFromSync || (!this.USER_DETAIL || this.disabledSwitcheEployee)) {
        return;
      }
      const tableData = this.modelForm.employeeId ? [this.modelForm.employeeId] : [];
      // const { selectCallback } = this;
      const condition = {};

      new this.$pageModal(
        SelectPerson,
        {
          props: {
            orgName: this.modelForm.orgName,
            orgId: this.modelForm.orgId,
            orgCode: this.modelForm.orgCode
          }
        },
        data => {
          if (data) {
            this.modelForm.employeeName = data.employeeName;
            this.modelForm.employeeId = data.employeeNo;
          }
        }
      );
    },
    // selectCallback(datas, target) {
    //   const employeeInfo = datas[0];
    //   this.employeeName = employeeInfo.name;
    //   this.modelForm.employeeId = employeeInfo.employeeNo;
    //   target.$emit("Close");
    // },
    _updateProcess(isSelf) {
      userManageAPI
        .updateUser(this.modelForm)
        .then(response => {
          if (!isSelf && this.userInfo.id === this.currentUserInfo.id) {
            sessionStorage.email = this.modelForm.email; //邮箱
            sessionStorage.mobile = this.modelForm.mobile; //手机号
            let Info = {
              userName: this.modelForm.userName,
              mobile: this.modelForm.mobile,
              email: this.modelForm.email,
              avatar: this.modelForm.avatar,
            }
            if (this.userInfo.orgId !== this.modelForm.orgId) {
              Info.orgId = this.modelForm.orgId
              Info.orgName = this.modelForm.orgName
            }
            this.setUserInfo(Info)
          }
          this.cussessCallBack(this.$t("common.updateSuccess"));
          if (isSelf) {
            window.$channel.$emit("LoginOut");
          }
        })
        .catch(() => {
          this.actions[0].loading = false;
        });
    },
    save() {
      this.$refs["editForm"].validate(valid => {
        if (valid) {
          this.actions[0].loading = true;
          if (this.userId) {
            // 编辑用户
            // 初始状态为有效
            if (this.initData.locked == "0") {
              let warningText;
              // 更改为无效时的提示
              if (this.modelForm.locked == "1") {
                const isSelf = this.userInfo.id === this.currentUserInfo.id;
                if (isSelf) {
                  warningText = this.$t("module.userManage.warning.disableSelf");
                } else {
                  warningText = this.$t("module.userManage.warning.disableUser");
                }
                this.$confirm
                  .swarning(warningText)
                  .then(() => {
                    this._updateProcess(isSelf);
                  })
                  .catch(() => {
                    this.actions[0].loading = false;
                  });
              } else if (this.cancelSelfBuiltApp.length != 0 || this.cancelThirdPartyApp.length != 0) {
                let cancelText = this.$t("module.userManage.warning.cancelApp");
                let selfBuiltText = this.$t("module.userManage.selfBuilt") + ":";
                let thirdPartyText = this.$t("module.userManage.thirdParty") + ":";
                // 取消分配的有效应用的提示
                if (this.cancelSelfBuiltApp != 0 && this.cancelThirdPartyApp.length != 0) {
                  warningText =
                    cancelText +
                    "\n" +
                    selfBuiltText +
                    this.cancelSelfBuiltApp +
                    "\n" +
                    thirdPartyText +
                    this.cancelThirdPartyApp;
                } else if (this.cancelSelfBuiltApp != 0 && this.cancelThirdPartyApp.length == 0) {
                  warningText = cancelText + "\n" + selfBuiltText + this.cancelSelfBuiltApp;
                } else if (this.cancelSelfBuiltApp == 0 && this.cancelThirdPartyApp.length != 0) {
                  warningText = cancelText + "\n" + thirdPartyText + this.cancelThirdPartyApp;
                } else {
                  warningText = cancelText;
                }

                this.$confirm
                  .swarning(warningText)
                  .then(() => {
                    this._updateProcess();
                  })
                  .catch(() => {
                    this.actions[0].loading = false;
                  });
              } else {
                this._updateProcess();
              }
            } else {
              this._updateProcess();
            }
          } else {
            // 新增用户
            let params = this.modelForm;
            params.type = 1;
            userManageAPI
              .addUser(params)
              .then(response => {
                this.cussessCallBack(this.$t("common.saveSuccess"));
              })
              .catch(() => {
                this.actions[0].loading = false;
              });
          }
        } else {
          // 错误提示： 表单验证未通过，请修改
          this.$message.error({
            content: this.$t("common.formValidateFailed"),
            duration: 3
          });
          return 0;
        }
      });
    },
    // 新增、编辑成功后执行函数
    cussessCallBack(text) {
      this.$message.success({
        content: text,
        duration: 3
      });
      this.$emit("Close", true);
    },
    // 切换用户类型时，显示隐藏所属租户
    handleUserCategory(value) {
      // 1.为平台管理员，隐藏选择所属组织功能
      if (value == 1) {
        this.clearOrganization();
        delete this.rule.orgName;
        delete this.rule.tenantCode;
      } else {
        let ruleTenantCode = [
          {
            required: true,
            message: this.$t("module.userManage.warning.selectTenantCode"),
            trigger: "change"
          }
        ];
        let ruleOrgName = [
          {
            required: true,
            message: this.$t("module.userManage.selectOrganization"),
            trigger: "change"
          }
        ];
        this.rule.tenantCode = ruleTenantCode;
        this.rule.orgName = ruleOrgName;
      }
      // 1. 为平台管理员，则显示所属租户字段，并清空字段
      // 2. 变更为租户管理员或普通用户，则隐藏所属租户，并默认为当前租户
      // 获取当前登录用户类型
      let currentTenantCode = this.currentUserInfo.tenantCode;
      let tenantCode = currentTenantCode || "";
      let isShow = false;
      switch (value) {
        case 1:
          tenantCode = currentTenantCode || window.RPConfig.rootTenantCode;
          break;
        case 2:
          if (currentTenantCode && currentTenantCode.toLowerCase() === RIPPLES) {
            isShow = true;
            tenantCode = "";
          }
          break;
      }
      this.showTenantCode = isShow;
      this.modelForm.tenantCode = tenantCode;
      this.tenantCodeAndUser.category = value;
      this.tenantCodeAndUser.tenantCode = tenantCode;
    },
    // 获取分配应用组件数据
    getSelectAllotApp(data) {
      const newSelected = data.selection;
      const newSelectedCode = newSelected.map(item => item.applicationCode);
      const oldSelectedCode = this.currentAppVos.map(item => item.applicationCode);
      //新增项
      const newAdded = newSelected.filter(item => oldSelectedCode.indexOf(item.applicationCode) == -1);
      //删除项
      const deletedApp = this.currentAppVos.filter(item => newSelectedCode.indexOf(item.applicationCode) == -1);
      this.modelForm.addAssignUserVos = newAdded;
      this.modelForm.delAssignUserVos = deletedApp;
    },
    // 当针对查询的数据进行取消或新增时，原来选择的数据会被置空，因此把新数据与原数据进行合并去重处理
    cancelOrAdd(selection, allCancelSelectApp, initData) {
      // 原来的选中数据
      let applicationCodes = initData;
      // 如存在新增数据
      if (selection.length != 0) {
        let data = applicationCodes.concat(selection);
        applicationCodes = Array.from(new Set(data));
      }
      // 如存在取消数据
      if (allCancelSelectApp.length != 0) {
        applicationCodes.map((item, index) => {
          if (allCancelSelectApp.indexOf(item) != -1) {
            applicationCodes.splice(index, 1);
          }
        });
      }
      return applicationCodes;
    },
    // 获取应用编码的对应数据
    getData(arr, data) {
      let result = [];
      for (let i in arr) {
        for (let j in data) {
          if (arr[i] == data[j].applicationCode) {
            result.push(data[j]);
          }
        }
      }
      return result;
    },
    initCategorySelect(state) {
      // 获取当前登录用户类型
      let tenantCode = this.currentUserInfo.tenantCode;
      // 根据当前用户类型显示相应用 - 户类型数据
      if (state) {
        // 是数字平台
        // 用户类型显示：平台管理员
        this.categoryList = this.categoryList.filter(item => item.value == 1);
        // 设置默认值：默认平台管理员
        this.modelForm.category = this.userInfo.category || 1;
        this.tenantCodeAndUser.category = this.modelForm.category;
        switch (this.modelForm.category) {
          case 1:
            this.showTenantCode = false;
            this.modelForm.tenantCode =
              this.userInfo.tenantCode || tenantCode.toLowerCase() === RIPPLES
                ? window.RPConfig.rootTenantCode
                : tenantCode;
            this.tenantCodeAndUser.tenantCode = this.modelForm.tenantCode;
            break;
          case 2:
            this.showTenantCode = true;
            break;
        }
      } else {
        // 用户类型显示：租户管理员、普通用户
        this.categoryList = this.categoryList.filter(item => item.value != 1);
        // 设置默认值：默认普通用户
        this.modelForm.category = this.userInfo.category || 3;
        this.tenantCodeAndUser.category = this.modelForm.category;
        this.showTenantCode = false;
        this.modelForm.tenantCode = this.userInfo.tenantCode || tenantCode;
        this.tenantCodeAndUser.tenantCode = this.modelForm.tenantCode;
      }
    }
  },
  watch: {},
  directives: {}
};
</script>
<style lang="less" scoped>
.editForm {
  background: #F4F6FD;
  .user-form {
    background: #fff;
    padding: 24px 24px 12px 24px;
    .ivu-row {
      margin-bottom: 0px;
      .last-item {
        margin-bottom: 0px;
      }
    }
    .user-form-title {
      display: block;
      font-size: 16px;
      color: #333333;
      letter-spacing: 0;
      font-weight: 600;
      margin-bottom: 20px;
    }
  }
  .role-assignment {
    background: #fff;
    margin-top: 18px;
    padding-bottom: 12px;
    /deep/.role-title {
      padding: 16px 24px;
      font-size: 16px;
      color: #333333;
      letter-spacing: 0;
      font-weight: 600;
    }
  }
  .user-app {
    background: #fff;
    margin-top: 10px;
    .app-title {
      padding: 24px;
      font-size: 16px;
      color: #333333;
      letter-spacing: 0;
      font-weight: 600;
      border-bottom: 1px solid #DCDEE0;
    }
    .AllotApp-page {
      padding: 0 20px 20px;
    }
  }
  .ivu-form-no-margin-bottom {
    .ivu-input-icon {
      line-height: 34px !important;
      font-size: 18px !important;
      cursor: pointer;
      -moz-transform: scaleX(-1);
      -webkit-transform: scaleX(-1);
      -o-transform: scaleX(-1);
      transform: scaleX(-1);
      /*IE*/
      filter: FlipH;
    }
  }
}
.user-img {
  display: flex;
  align-items: end;
  .upload-icon {
    width:80px;
    height:80px;
    line-height:80px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  p {
    padding-left: 10px
  }

}
  .img-item {
    display: inline-block;
    position: relative;
    height: 80px;
    .demo-upload-list-cover{
      display: none;
      position: absolute;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
      background: rgba(0,0,0,.6);
    }
    &:hover .demo-upload-list-cover{
      display: flex;
      justify-content: center;
      align-items: center;
    }
    .demo-upload-list-cover i{
      color: #fff;
      font-size: 20px;
      cursor: pointer;
      margin: 0 2px;
    }
  }
</style>
